import "dotenv/config";
import express from "express";
import http from "http";
import { Server } from "socket.io";
import cors from "cors";
import helmet from "helmet";
import morgan from "morgan";
import path from "path";

// 路由
import auth from "./routes/auth";
import map from "./routes/map";
import heatmap from "./routes/heatmap";
import routePlan from "./routes/route";
import simulate from "./routes/simulate";
import optimize from "./routes/optimize";
import assets from "./routes/assets";
import scene from "./routes/scene";
import alerts from "./routes/alerts";
import drug from "./routes/drug";
import ocr from "./routes/ocr";
import cloudrender from "./routes/cloudrender";
import admin from "./routes/admin";
import face from "./routes/face";
import email from "./routes/email";
import patientAuth from "./routes/patient-auth";
import wxappAuth from "./routes/wxapp-auth";
import adminWxapp from "./routes/admin-wxapp";
import location from "./routes/location";
import appointment from "./routes/appointment";
import ai from "./routes/ai";
import patientStats from "./routes/patient-stats";
import hospitalSite from "./routes/hospital-site";
import banner from "./routes/banner";
import { authenticateWxAppToken } from "./middleware/wxapp-auth";
import { authenticateToken } from "./middleware/auth";

// MongoDB 相关导入
import { initializeMongoDB, createSampleData, startPeriodicSync } from "./utils/mongodb-init";
import { mongoDBMiddleware, mongoDBLogger, ocrRecordMiddleware, userSyncMiddleware } from "./middleware/mongodb-integration";
import mongodbTest from "./routes/mongodb-test";

const app = express();

// 增强CORS配置，支持小程序访问
app.use(cors({
  origin: process.env.CORS_ORIGIN || "*",
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'Accept', 'Origin', 'User-Agent'],
  exposedHeaders: ['Content-Length', 'Content-Type']
}));

// 配置helmet，允许跨域资源
app.use(helmet({
  crossOriginResourcePolicy: { policy: "cross-origin" },
  crossOriginEmbedderPolicy: false,
  contentSecurityPolicy: false // 禁用CSP避免阻止小程序访问
}));

app.use(express.json({ limit: "2mb" }));
app.use(express.urlencoded({ extended: true, limit: "2mb" }));
app.use(morgan("dev"));

// 添加 MongoDB 中间件（可选，不影响现有功能）
app.use(mongoDBMiddleware);        // 确保 MongoDB 连接
app.use(mongoDBLogger);            // 自动记录 API 日志到 MongoDB
app.use(ocrRecordMiddleware);      // 自动记录 OCR 处理结果到 MongoDB
app.use(userSyncMiddleware);       // 自动同步用户数据到 MongoDB

// 调试中间件
app.use((req, res, next) => {
  if (req.path.includes('/liveness')) {
    console.log(`[DEBUG] ${req.method} ${req.path}`);
    console.log(`[DEBUG] Content-Type: ${req.get('Content-Type')}`);
    console.log(`[DEBUG] Body:`, req.body);
  }
  next();
});

// 配置静态文件服务 - 添加完整CORS支持
app.use('/static', (req, res, next) => {
  // 处理预检请求
  if (req.method === 'OPTIONS') {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
    res.header('Access-Control-Max-Age', '3600');
    res.status(200).send();
    return;
  }
  
  // 为静态文件添加CORS头
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  res.header('Cross-Origin-Resource-Policy', 'cross-origin');
  res.header('Cross-Origin-Embedder-Policy', 'unsafe-none');
  res.header('Vary', 'Origin');
  
  next();
}, express.static(path.join(process.cwd(), '../wxapp/static'), {
  // 静态文件选项
  maxAge: '1d', // 缓存1天
  etag: false,
  lastModified: true
}));

app.use('/uploads', (req, res, next) => {
  // 处理预检请求
  if (req.method === 'OPTIONS') {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
    res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
    res.header('Access-Control-Max-Age', '3600');
    res.status(200).send();
    return;
  }
  
  // 为上传文件添加CORS头
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'GET, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  res.header('Cross-Origin-Resource-Policy', 'cross-origin');
  res.header('Cross-Origin-Embedder-Policy', 'unsafe-none');
  res.header('Vary', 'Origin');
  next();
}, express.static(path.join(process.cwd(), 'uploads'), {
  maxAge: '1d',
  etag: false,
  lastModified: true
}));

// v1 API路由
app.use("/v1/auth", auth);
app.use("/v1/map", map);
app.use("/v1/heatmap", heatmap);
app.use("/v1/route", routePlan);
app.use("/v1/simulate", simulate);
app.use("/v1/optimize", optimize);
app.use("/v1/assets", assets);
app.use("/v1/scene", scene);
app.use("/v1/ocr", ocr);
app.use("/v1/cloudrender", cloudrender);
app.use("/v1/admin", admin);
app.use("/v1/face", face);
app.use("/v1/email", email);
app.use("/v1/alerts", alerts);
app.use("/v1/drug", drug);
app.use("/v1/patient", patientAuth);
app.use("/v1/location", location);
app.use("/v1/appointment", appointment);
app.use("/v1/ai", ai);
app.use("/v1/patient-stats", patientStats);
app.use("/v1/hospital-site", hospitalSite);
app.use("/v1/banner", banner);

// API路由（为小程序兼容性添加）
app.use("/api/ocr", ocr);
app.use("/v1/api/ocr", ocr);  // 添加v1前缀的API路由，保持前端数据完整性

// wxapp API 路由（MongoDB 入口同样需要挂载）
// 注意：只挂载一次基础前缀，路由细分在 wxapp-auth.ts 内部定义
app.use("/api/wxapp/auth", wxappAuth);
// 管理端 wxapp 用户管理（需要管理端鉴权）
app.use("/api/admin", authenticateToken, adminWxapp);

// 添加 MongoDB 测试路由
app.use("/v1/mongodb", mongodbTest);

// 健康检查接口
app.get("/health", (req, res) => {
  res.json({ 
    status: "ok", 
    timestamp: new Date().toISOString(),
    version: "1.0.0"
  });
});

const server = http.createServer(app);
const io = new Server(server, { cors: { origin: process.env.CORS_ORIGIN || "*" } });

// WebSocket 命名空间
io.of("/ws/simulate").on("connection", (s) => {
  s.emit("progress", { runId: "r_demo", progress: 10, eta: 120 });
});
io.of("/ws/alerts").on("connection", (s) => {
  s.emit("alert.new", { id: "a1", type: "crowd", level: "L1", startedAt: new Date().toISOString() });
});
io.of("/ws/viewer").on("connection", (s) => {
  s.on("control", (msg) => s.broadcast.emit("control", msg));
});

const port = Number(process.env.PORT || 8080);
server.listen(port, async () => {
  console.log(`[api] listening on :${port}`);
  
  // 初始化 MongoDB（异步，不阻塞服务器启动）
  initializeMongoDB().then(() => {
    // 创建示例数据（仅在开发环境）
    createSampleData();
    
    // 启动定期同步任务
    startPeriodicSync();
    
    console.log('[服务器] ✅ MongoDB 集成完成');
  }).catch((error) => {
    console.error('[服务器] ⚠️ MongoDB 初始化失败，服务器将继续运行:', error.message);
  });
});